package Leave

import (
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"go.uber.org/zap"
	"project/pkg/models"
	"project/pkg/validate"
	"strconv"
)

func (h LHandler) CreateWx(c *gin.Context) {
	resp := new(models.RespData)
	req := new(models.LeaveUpdateReq)
	if err := c.ShouldBindJSON(req); err != nil {
		errs, ok := err.(validator.ValidationErrors)
		if !ok {
			zap.L().Error("Student:Update with invalid fail", zap.Error(err))
			resp.SendServerBusy(c)
			return
		} else {
			zap.L().Error("Student:Update with invalid fail", zap.Error(errs))
			resp.SendCodeWithMsg(c, models.CodeInvalidParam, validate.RemoveTopStruct(errs.Translate(validate.Trans)))
			return
		}
	}
	//fmt.Printf("%+v", req)
	leave := &models.LeaveInfo{
		RequestID:        req.RequestID,
		RequestName:      req.RequestName,
		RequestCLassID:   req.RequestCLassID,
		RequestCLassName: req.RequestCLassName,
		BeginTime:        req.BeginTime,
		EndTime:          req.EndTime,
		Msg:              req.Msg,
		TeacherId:        req.TeacherId,
		TeacherName:      req.TeacherName,
		Action:           req.Action,
	}
	//更新学生信息
	exist, info, err := h.M.StudentCheckExistByOpenID(leave.RequestID)
	if err != nil {
		zap.L().Error("Leave:UpdateInfo h.M.StudentCheckExistByOpenID err", zap.Error(err))
		resp.SendServerBusy(c)
		return
	}
	if exist {
		count, _ := strconv.Atoi(info.LeaveInfoCount)
		now := count + 1
		info.LeaveInfoCount = strconv.Itoa(now)
		err := h.M.StudentUpdateInfoBuID(info)
		if err != nil {
			zap.L().Error("Leave:UpdateInfo h.M.StudentUpdateInfoBuID err", zap.Error(err))
			resp.SendServerBusy(c)
			return
		}
	}
	//更新信息
	err = h.M.LeaveUpdateInfoBuID(leave)
	if err != nil {
		zap.L().Error("Leave:UpdateInfo h.M.LeaveUpdateInfoBuID err", zap.Error(err))
		resp.SendServerBusy(c)
		return
	}
	resp.SendSuccess(c)
}
